package com.itheima.model;

import com.itheima.bean.User;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class UserModel {

    private static String usersDataPath = "take-away-system/src/com/itheima/data/users.oxt";

    // 获取一个用户，根据用户名
    public static User getUser(String username) throws IOException, ClassNotFoundException {
        // 1. 获取用户列表
        final List<User> users = getUsers();

        // 2. 查找该用户
        for (User user : users) {
            if (username.equals(user.getUsername())) {
                return user;
            }
        }

        // 3. 返回值
        return null;
    }

    // 读取用户列表
    public static List<User> getUsers () throws IOException, ClassNotFoundException {
        try {
            // 1. 序列号流读取
            final ObjectInputStream ois = new ObjectInputStream(new FileInputStream(usersDataPath));

            // 2. 得到列表
            final List<User> users = (List<User>) ois.readObject();

            // 3. 关闭流
            ois.close();

            return users;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            List<User> users = new ArrayList<>();
            return users;
        } catch (FileNotFoundException e) {
            // 文件不存在的话需要新建空文件
            List<User> users = new ArrayList<>();
            saveUsers(users);
            return users;
        }
    }

    // 保存用户列表
    public static void saveUsers(List<User> users) throws IOException {
        // 1. 序列流读取
        final ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(usersDataPath));

        // 2. 写入
        oos.writeObject(users);

        // 3. 关闭流
        oos.close();
    }
}
